package Demo1;

import javax.servlet.*;
import java.awt.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Objects;

/**
 * ServletContext接口是由tomcat实现的,Servlet对象是在tomcat启动时创建的.对于一个webapp来说,ServletContext对象只有一个
 * 并且是在tomcat服务器关闭时销毁.
 *
 * ServletContext是servlet对象的上下文对象.
 * ServletContext对象其实就是整个web.xml文件.
 * 一间教室里的学生就像servlet对象,整个教室就是ServletContext对象.
 * 在ServletCOntext对象中的属性,一定是所有的servlet都是可以共享的
 *
 * 比如:tomcat是一个容器,在WEB容器中可以有多个项目,每一个项目都有一个ServletContext对象
 */

public class ServletContexta extends GenericServlet {
    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html");
         PrintWriter out = res.getWriter();
        ServletContext application = this.getServletContext();

        out.print("this is "+application);
         Enumeration<String> stringEnumeration = application.getInitParameterNames();
         while(stringEnumeration.hasMoreElements()){

             String name = stringEnumeration.nextElement();
             String value = application.getInitParameter(name);
             out.print(name+"   "+value +"<br>");
        }

         // 此方法用于获取根
         String path = application.getContextPath();
         out.print(path);

         // 查找文件的绝对路径
         String realPath = application.getRealPath("/web/WEB-INF/web.xml");
         out.print(realPath);
        System.out.println(realPath);


//        application.log("this is my first logs! look at me!!");

        User userobj1 = new User("jack",17);
         User userobj2 = new User("anni",12);
        application.setAttribute("userObj1",userobj1);
        application.setAttribute("userObj2",userobj2);
        application.removeAttribute("userObj1");
//
//        Object object1 = application.getAttribute("userObj1");
//        Object object2 = application.getAttribute("userObj2");
//        System.out.println(object1);
//        System.out.println(object2);
//        out.print(object1);
//        out.print(object2);

    }
}
